<?php

namespace AgilePayments\Apple;

use AgilePayments\Config;
use think\Request;
use AgilePayments\Tool;

class Service
{
    private $config;

    private $app_id;

    private $appCertPath;

    private $alipayCertPath;

    private $rootCertPath;

    private $rsaPrivateKey;

    private $alipayrsaPublicKey;

    protected $appleCode = [
        21000 => 'App Store无法读取你提供的JSON数据',
        21002 => '收据数据不符合格式',
        21003 => '收据无法被验证',
        21004 => '你提供的共享密钥和账户的共享密钥不一致',
        21005 => '收据服务器当前不可用',
        21006 => '收据是有效的，但订阅服务已经过期。当收到这个信息时，解码后的收据信息也包含在返回内容中',
        21007 => '收据信息是测试用（sandbox），但却被发送到产品环境中验证',
        21008 => '收据信息是产品环境中使用，但却被发送到测试环境中验证'
    ];
    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * @desc 回调验证数据
     */
    public function verifySign($request)
    {
        $receipt = input('receipt','');
        $payOrderId = input('payOrderId','');
        if ($receipt == '' || $payOrderId == ''){
            return ['status'=> false, 'msg' => '缺少必要参数[receipt|payOrderId]'];
        }

        $time = time();
        Tool::log("notifyLog/notifyProcessLog".date("Ymd", $time).".log", "\n" . date("Y-m-d H:i:s", $time) . "，支付凭证：" . $receipt, FILE_APPEND);

        $jsonItem = json_encode(['receipt-data' => $receipt]);

        $url = 'https://buy.itunes.apple.com/verifyReceipt';      //正式

        //模拟post提交（下面会贴出来），将前端获取到的凭证，去和苹果换取详细的支付信息
        $result = $this->http_post_json($jsonItem, $url);

        if ($result['status'] == '21007') {
            //验证失败 返回app错误状态
            $url = 'https://sandbox.itunes.apple.com/verifyReceipt';  //测试
            $result = $this->http_post_json($jsonItem, $url);
        }
        Tool::log("notifyLog/notifyProcessLog".date("Ymd", $time).".log", "\n" . date("Y-m-d H:i:s", $time) . "，order：" . var_export($result, true), FILE_APPEND);
        //如果检测到 等于 0 就是支付成功，其他的错误码去获取对应错误信息
        if ($result['status'] !== 0) {
            //验证失败 返回app错误状态
            return ['status'=>false,'msg'=>$this->appleCode[$result['status']]];
        }
        //接下来就是做自己的业务逻辑　　　　　　　　

        return ['status'=>true,'msg'=>'支付成功','payOrderId' => $payOrderId, 'query_id'=> '', 'trade_no' => ''];

    }
    //模拟post提交
    public function http_post_json($json, $url)
    {

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);  //这两行一定要加，不加会报SSL 错误
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        $errmsg = curl_error($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        return $data;
    }

    public function returnSuccess()
    {
        return;
    }

}